﻿using System;
using System.Configuration.Provider;
using System.Collections;
using System.Collections.Specialized;
using System.IO;
using System.Security.Permissions;
using System.Web;
using Commerce.Data;
using Commerce.Services;
using System.Collections.Generic; 
namespace Commerce.CSK.Web
{
    public class CatalogSiteMapProvider : System.Web.StaticSiteMapProvider
    {
        public override SiteMapNode BuildSiteMap()
        {
            return RootNode; 
        }

        protected override SiteMapNode GetRootNodeCore()
        {
            return RootNode;
        }

        private SiteMapNode _rootNode; 
        public override SiteMapNode RootNode
        {
            get
            {
                if (_rootNode == null)
                {
                    lock (this)
                    {
                        _rootNode = BuildRootNode(); 
                    }
                }
                return _rootNode; 
            }
        }

        private SiteMapNode BuildRootNode()
        {
            ICatalogService catalog = Services.GetCatalogService();
            IList<Category> categoryList = catalog.GetCategories();
            SiteMapNode _root = new SiteMapNode(this, "default");
            AddNode(_root); 
            foreach (var category in categoryList)
            {
                AddCategoryNode(_root, category, false); 
            }
            return _root; 
        }
        private void AddCategoryNode(SiteMapNode parentNode, Category newCategory, bool showLink)
        {

            string url = String.Empty; 
            if(showLink)
            {
                url = Links.GetCategoryViewLink(newCategory);
            }
            SiteMapNode categoryNode = new SiteMapNode(this, 
                newCategory.ID.ToString(), 
                url,
                newCategory.Name);
            this.AddNode(categoryNode, parentNode);
            if (newCategory.SubCategories != null)
            {
                foreach (var child in newCategory.SubCategories)
                {
                    AddCategoryNode(categoryNode, child, true);
                }
            }
        }
    }
}